/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "AuthCrypt.h"
#include <cstring>
#include <algorithm>
#include <NodeCpp/Crypto/Hmac.h>
using NodeCpp::Crypto::HmacHash;

AuthCrypt::AuthCrypt(void)
	: Key_()
	, Send_i_(0)
	, Send_j_(0)
	, Recv_i_(0)
	, Recv_j_(0)
	, Inited_(false)
{

}

AuthCrypt::~AuthCrypt(void)
{

}

void AuthCrypt::Init(void)
{
	Send_i_ = Send_j_ = Recv_i_ = Recv_j_ = 0;
	Inited_ = true;
}

void AuthCrypt::SetKey(std::uint8_t *_Key, std::size_t _Size)
{
	Key_.resize(_Size);
	std::copy(_Key, _Key + _Size, Key_.begin());
}

void AuthCrypt::DecryptRecv(std::uint8_t *_Data, std::size_t _Size)
{
	if (!Inited_) { return; }
	if (_Size < CRYPTED_RECV_LEN) { return; }

	for (std::size_t _T = 0; _T < CRYPTED_RECV_LEN; _T++)
	{
		Recv_i_ %= Key_.size();
		std::uint8_t _X = (_Data[_T] - Recv_j_) ^ Key_[Recv_i_];
		++Recv_i_;
		Recv_j_ = _Data[_T];
		_Data[_T] = _X;
	}
}

void AuthCrypt::EncryptSend(std::uint8_t *_Data, std::size_t _Size)
{
	if (!Inited_) { return; }
	if (_Size < CRYPTED_SEND_LEN) { return; }

	for (std::size_t _T = 0; _T < CRYPTED_SEND_LEN; _T++)
	{
		Send_i_ %= Key_.size();
		std::uint8_t _X = (_Data[_T] ^ Key_[Send_i_]) + Send_j_;
		++Send_i_;
		_Data[_T] = Send_j_ = _X;
	}
}

void AuthCrypt::GenerateKey(std::uint8_t *_Key, BigNumber *_Bn)
{
	HmacHash _Hash;
	_Hash.UpdateBigNumber(_Bn);
	_Hash.Finalize();
	memcpy(_Key, _Hash.digest(), SHA_DIGEST_LENGTH);
}
